package com.zhehekeji.opsys.api.service.manager;

import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.zhehekeji.opsys.api.code.LuckyDrawResultCode;
import com.zhehekeji.opsys.api.common.util.DateFormatUtil;
import com.zhehekeji.opsys.api.conf.Config;
import com.zhehekeji.opsys.api.entity.TActivity;
import com.zhehekeji.opsys.api.entity.TPrize;
import com.zhehekeji.opsys.api.entity.TUser;
import com.zhehekeji.opsys.api.entity.TWinningResult;
import com.zhehekeji.opsys.api.entity.TWinningRule;
import com.zhehekeji.opsys.api.resp.CheckActivityResp;
import com.zhehekeji.opsys.api.resp.GetActivityListResp;
import com.zhehekeji.opsys.api.resp.GetActivityResp;
import com.zhehekeji.opsys.api.resp.GetDrawRecordCountByMobileResp;
import com.zhehekeji.opsys.api.resp.GetDrawRecordCountResp;
import com.zhehekeji.opsys.api.resp.GetDrawRecordResp;
import com.zhehekeji.opsys.api.resp.GetPrizeListResp;
import com.zhehekeji.opsys.api.resp.GetWinningResultListResp;
import com.zhehekeji.opsys.api.resp.LuckyDrawResp;
import com.zhehekeji.opsys.api.resp.UpdateWinningResultResp;
import com.zhehekeji.opsys.api.service.CommonService;
import com.zhehekeji.opsys.api.service.PrizeService;
import com.zhehekeji.opsys.api.service.validate.ActivityValidate;
import com.zhehekeji.opsys.api.service.validate.UserDrawValidate;
import com.zhehekeji.opsys.api.service.validate.ValidateRets;
import com.zhehekeji.opsys.api.service.validate.WinningRuleValidate;
import com.zhehekeji.opsys.api.service.validate.args.ActivityValidateArgs;
import com.zhehekeji.opsys.api.service.validate.args.LuckyDrawArgs;
import com.zhehekeji.opsys.api.service.validate.args.UserValidateArgs;
import com.zhehekeji.opsys.api.service.validate.args.WinningRuleValidateArgs;

/**
 * @ClassName ActivityManagerService
 * @Description TODO
 * @author chenweiliu chenwei.liu@163.com
 * @date 2015-4-7   上午10:35:04
 */
@Service
public class ActivityManagerService extends CommonService {
	
	private final static Logger logger = LoggerFactory.getLogger(ActivityManagerService.class);
	
	@Autowired
	private ActivityValidate activityValidate;
	@Autowired
	private WinningRuleValidate winningRuleValidate;
	@Autowired
	private UserDrawValidate userDrawValidate;
	@Autowired
	private PrizeService prizeService;
	@Autowired
	private Config config;
	
	public CheckActivityResp checkActivity(String activityCode){
		CheckActivityResp resp = new CheckActivityResp();
		logger.info("checkActivity activityCode="+activityCode);
		try{
			Date currentDate = new Date();
			 ValidateRets<TActivity> tmpTActivityValidateRets = activityValidate.validate(new ActivityValidateArgs(resp, activityCode, currentDate));
			 if (!tmpTActivityValidateRets.isSuccess()) return resp;
			 logger.info("验证活动成功");
		}catch (Exception e){
			logger.error("程序异常，", e);
			resp.setResultCode(LuckyDrawResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("程序异常");
		}
		return resp;
	}
	
	public GetActivityResp getActivity(String activityCode){
		logger.info("获取活动Code="+activityCode);
		GetActivityResp resp = new GetActivityResp();
		if (StringUtils.isBlank(activityCode)){
			logger.error("活动编码非法！");
			resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc("活动编码非法！");
			return resp;
		}
		try {
			TActivity tmpTActivity = entityDao.get(TActivity.class, "code=?1", new Object[]{activityCode});
			if (tmpTActivity == null){
				logger.error("活动不存在，活动编码非法！");
				resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
				resp.setResultDesc("活动不存在，活动编码非法！");
				return resp;
			}
			Integer tmpStatus = tmpTActivity.getStatus();
			if (tmpStatus == 0){
				logger.error("活动已经停用！");
				resp.setResultCode(LuckyDrawResultCode.ACTIVITY_HAS_BEEN_STOPPED);
				resp.setResultDesc("活动已经停用！");
				return resp;
			}
			resp.setCode(activityCode);
			resp.setEndTime(DateFormatUtil.format(tmpTActivity.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
			resp.setName(tmpTActivity.getName());
			resp.setObjects(tmpTActivity.getObjects());
			resp.setPurpose(tmpTActivity.getPurpose());
			resp.setStartTime(DateFormatUtil.format(tmpTActivity.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
			resp.setTheme(tmpTActivity.getTheme());
			resp.setRepeatWinning(tmpTActivity.getRepeatWinning());
			resp.setUseupPoint(tmpTActivity.getUseupPoint());
			resp.setCpCode(tmpTActivity.getCpCode());
			if (!StringUtils.isBlank(tmpTActivity.getActivityDiagram())){
				resp.setActivityDiagram(getHttpUrl(tmpTActivity.getActivityDiagram()));
			}
			if (!StringUtils.isBlank(tmpTActivity.getActivityIcon())){
				resp.setActivityIcon(getHttpUrl(tmpTActivity.getActivityIcon()));
			}
			if (!StringUtils.isBlank(tmpTActivity.getActivityPoster())){
				resp.setActivityPoster(getHttpUrl(tmpTActivity.getActivityPoster()));
				resp.setImgAddress(config.getImgAddress());//getHttpUrl(config.getImgAddress(), tmpTActivity.getActivityPoster())
			}
			logger.info("获取活动信息成功");
		} catch (Exception e) {
			logger.error("程序异常，", e);
			resp.setResultCode(LuckyDrawResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("程序异常");
		}
		return resp;
	}
	
	public GetActivityListResp getActivityList(Long cpCode){
		logger.info("getActivityList cpCode="+cpCode);
		GetActivityListResp resp = new GetActivityListResp();
		if (cpCode == null){
			logger.error("cpCode非法！");
			resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc("cpCode非法！");
			return resp;
		}
		String tmpWhereJpql = null;
		if (cpCode != -1){
			tmpWhereJpql = "o.cpCode=" +cpCode + " and o.status=1 and o.epgDisplay=1";
		}else{
			//状态：启用 且 EPG控制：显示
			tmpWhereJpql = "o.status=1 and o.epgDisplay=1";
		}
		try {
			List<TActivity> tmpListTActivity = entityDao.getScrollData(TActivity.class, tmpWhereJpql, null);
			if (tmpListTActivity == null || tmpListTActivity.isEmpty()){
				return resp;
			}
			List<GetActivityListResp.ActivityInfo> tmpListActivityInfo = new ArrayList<GetActivityListResp.ActivityInfo>();
			GetActivityListResp.ActivityInfo tmpActivityInfo;
			for (TActivity tmpTActivity : tmpListTActivity){
				tmpActivityInfo = new GetActivityListResp.ActivityInfo();
				tmpActivityInfo.setCode(tmpTActivity.getCode());
				tmpActivityInfo.setEndTime(DateFormatUtil.format(tmpTActivity.getEndTime(), "yyyy-MM-dd HH:mm:ss"));
				tmpActivityInfo.setName(tmpTActivity.getName());
				tmpActivityInfo.setObjects(tmpTActivity.getObjects());
				tmpActivityInfo.setPurpose(tmpTActivity.getPurpose());
				tmpActivityInfo.setStartTime(DateFormatUtil.format(tmpTActivity.getStartTime(), "yyyy-MM-dd HH:mm:ss"));
				tmpActivityInfo.setTheme(tmpTActivity.getTheme());
				tmpActivityInfo.setRepeatWinning(tmpTActivity.getRepeatWinning());
				tmpActivityInfo.setUseupPoint(tmpTActivity.getUseupPoint());
				tmpActivityInfo.setCpCode(tmpTActivity.getCpCode());
				if (!StringUtils.isBlank(tmpTActivity.getActivityDiagram())){
					tmpActivityInfo.setActivityDiagram(getHttpUrl(tmpTActivity.getActivityDiagram()));
				}
				if (!StringUtils.isBlank(tmpTActivity.getActivityIcon())){
					tmpActivityInfo.setActivityIcon(getHttpUrl(tmpTActivity.getActivityIcon()));
				}
				if (!StringUtils.isBlank(tmpTActivity.getActivityPoster())){
					tmpActivityInfo.setActivityPoster(getHttpUrl(tmpTActivity.getActivityPoster()));
					tmpActivityInfo.setImgAddress(config.getImgAddress());//getHttpUrl(config.getImgAddress(), tmpTActivity.getActivityPoster())
				}
				tmpListActivityInfo.add(tmpActivityInfo);
			}
			resp.setActivityInfos(tmpListActivityInfo);
			resp.setRecordSize(tmpListActivityInfo.size());
			logger.info("获取活动列表成功");
		} catch (Exception e) {
			logger.error("程序异常，", e);
			resp.setResultCode(LuckyDrawResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("程序异常");
		}
		return resp;
	}
	
	
	public GetPrizeListResp getPrizeList(String activityCode){
		logger.info("获取奖品， 活动code="+activityCode);
		GetPrizeListResp resp = new GetPrizeListResp();
		String resultDesc = String.format("活动编码[%s]非法！", activityCode);
		if (StringUtils.isBlank(activityCode)){
			logger.error(resultDesc);
			resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc(resultDesc);
			return resp;
		}
		try {
			TActivity tmpTActivity = entityDao.get(TActivity.class, "o.code=?1", new Object[]{activityCode});
			if (tmpTActivity == null){
				logger.error(resultDesc);
				resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
				resp.setResultDesc(resultDesc);
				return resp;
			}
			
			String tmpSql = "select o.CODE as code,o.NAME as name,o.TYPE as type,o.LEVEL as level, o.LIMIT_NUM as limitNum,"
					+ "o.NUMBER as number,o.WINNING_NUM as winningNum,o.PRICE as price,"
					+ "o.ODDS as odds,o.PICTURE as picture from t_prize o "
					+ "where o.ACTIVITY_ID=" + tmpTActivity.getId() + " and o.STATUS=1 order by o.LEVEL asc";
			List<Map<String, Object>> tmpListMap = entityDao.getScrollDataBySql(tmpSql, null, -1, -1);
			if (tmpListMap == null || tmpListMap.isEmpty()){
				return resp;
			}
			List<GetPrizeListResp.PrizeInfo> tmpListPrizeInfo = new ArrayList<GetPrizeListResp.PrizeInfo>();
			GetPrizeListResp.PrizeInfo tmpPrizeInfo;
			String tmpPicture;
			for (Map<String, Object> tmpMap : tmpListMap){
				tmpPrizeInfo = new GetPrizeListResp.PrizeInfo();
				tmpPrizeInfo.setCode((String)tmpMap.get("code"));
				tmpPrizeInfo.setLevel((Integer)tmpMap.get("level"));
				tmpPrizeInfo.setLimitNum((Integer)tmpMap.get("limitNum"));
				tmpPrizeInfo.setName((String)tmpMap.get("name"));
				tmpPrizeInfo.setNumber((Integer)tmpMap.get("number"));
				tmpPrizeInfo.setOdds((Float)tmpMap.get("odds"));
				tmpPicture = (String)tmpMap.get("picture");
				if (!StringUtils.isBlank(tmpPicture)){
					tmpPrizeInfo.setPicture(getHttpUrl(tmpPicture));
					tmpPrizeInfo.setImgAddress(config.getImgAddress());//getHttpUrl(config.getImgAddress(), tmpPicture)
				}
				tmpPrizeInfo.setPrice((Integer)tmpMap.get("price"));
				tmpPrizeInfo.setWinningNum((Integer)tmpMap.get("winningNum"));
				tmpListPrizeInfo.add(tmpPrizeInfo);
			}
			resp.setTprizeList(tmpListPrizeInfo);
			logger.info("获取奖品列表成功");
		} catch (Exception e) {
			logger.error("获取奖品列表失败，程序异常，", e);
			resp.setResultCode(LuckyDrawResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("获取奖品列表失败，程序异常！");
		}
		return resp;
	}

	public GetWinningResultListResp getWinningResultList(String activityCode, int firstIndex, int maxResult){
		GetWinningResultListResp resp = new GetWinningResultListResp();
		logger.info("getWinningResultList activityCode="+activityCode+",firstIndex="+firstIndex+",maxResult"+maxResult);
		if (StringUtils.isBlank(activityCode)){
			logger.error(String.format("活动编码[%s]非法！", activityCode));
			resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc(String.format("活动编码[%s]非法！", activityCode));
			return resp;
		}
		try {
			TActivity tmpTActivity;
			String tmpActivityIds = "";
			String[] tmpActivityCodes = activityCode.split(",");
			String tmpSql;
			List<Map<String, Object>> tmpListMap;
			Map<Long, TActivity> tmpIdActLinkMap = new HashMap<Long, TActivity>();
			if (tmpActivityCodes.length == 1){
				tmpTActivity = entityDao.get(TActivity.class, "o.code=?1", new Object[]{activityCode});
				if (tmpTActivity == null){
					logger.error(String.format("活动编码[%s]非法！", activityCode));
					resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
					resp.setResultDesc(String.format("活动编码[%s]非法！", activityCode));
					return resp;
				}
				tmpIdActLinkMap.put(tmpTActivity.getId(), tmpTActivity);
				tmpActivityIds = tmpTActivity.getId() + "";
				tmpSql = "select count(o.ID) as count from t_winning_result o where o.ACTIVITY_ID=" + tmpTActivity.getId();
				tmpListMap = entityDao.getScrollDataBySql(tmpSql, null, -1, -1);
			}else{
				String tmpActivityCode;
				for (int i=0; i<tmpActivityCodes.length;i++){
					tmpActivityCode = tmpActivityCodes[i];
					tmpTActivity = entityDao.get(TActivity.class, "o.code=?1", new Object[]{tmpActivityCode});
					if (tmpTActivity == null){
						logger.error(String.format("活动编码[%s]非法！", tmpActivityCode));
						resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
						resp.setResultDesc(String.format("活动编码[%s]非法！", tmpActivityCode));
						return resp;
					}
					tmpIdActLinkMap.put(tmpTActivity.getId(), tmpTActivity);
					tmpActivityIds = tmpActivityIds + tmpTActivity.getId() + ",";
				}
				tmpActivityIds = org.apache.commons.lang.StringUtils.removeEnd(tmpActivityIds, ",");
				tmpSql = "select count(o.ID) as count from t_winning_result o where o.ACTIVITY_ID in(" + tmpActivityIds + ")";
				tmpListMap = entityDao.getScrollDataBySql(tmpSql, null, -1, -1);
			}
			
			int  tmpIntCount = 0;
			if (tmpListMap != null && !tmpListMap.isEmpty()){
				Map<String, Object> tmpMapCount = tmpListMap.get(0);
				BigInteger tmpLongCount = (BigInteger) tmpMapCount.get("count");
				tmpIntCount = tmpLongCount.intValue();
			}
			if(tmpIntCount <= 0) return resp;
			 
			
			tmpSql = "select o.ACTIVITY_ID as activityId,o.PRIZE_ID as prizeId,o.ACCOUNT as account,o.MOBILE as mobile, o.WINNING_TIME as winningTime,"
					+ "o.CP_CODE as cpCode,o.CARD_NO as cardNo,o.CARD_PWD as cardPwd from t_winning_result o ";
			if (tmpActivityCodes.length == 1){
				tmpSql = tmpSql + " where o.ACTIVITY_ID=" + NumberUtils.toLong(tmpActivityIds) + " order by o.WINNING_TIME desc";
			}else{
				tmpSql = tmpSql + " where o.ACTIVITY_ID in (" + tmpActivityIds + ") order by o.WINNING_TIME desc";
			}
			tmpListMap = entityDao.getScrollDataBySql(tmpSql, null, firstIndex, maxResult);
			if (tmpListMap == null || tmpListMap.isEmpty()){
				return resp;
			}
			
			Map<Long, TPrize> tmpPrizeMap = new HashMap<Long, TPrize>();
			TPrize tmpTPrize;
			List<GetWinningResultListResp.WinningResultInfo> tmpListWinningResultInfo = new ArrayList<GetWinningResultListResp.WinningResultInfo>();
			GetWinningResultListResp.WinningResultInfo tmpWinningResultInfo;
			tmpSql = "select o.CODE as prizeCode,o.NAME as prizeName,o.LEVEL as prizeLevel,o.PICTURE as prizePicture "
				   + "from t_prize o where o.ID=%s";
			Long prizeId;
			List<Map<String, Object>> tmpListObjectMap;
			Map<String, Object> tmpObjectMap;
			Date tmpWinningTime;
			BigInteger tmpBig;
			for (Map<String, Object> tmpMap : tmpListMap){
				tmpWinningResultInfo = new GetWinningResultListResp.WinningResultInfo();
				tmpBig = (BigInteger)tmpMap.get("activityId");
				if (tmpBig != null){
					tmpTActivity = tmpIdActLinkMap.get(tmpBig.longValue());
					if (tmpTActivity != null){
						tmpWinningResultInfo.setActivityCode(tmpTActivity.getCode());
						tmpWinningResultInfo.setActivityName(tmpTActivity.getName());
					}
				}
				tmpBig = (BigInteger)tmpMap.get("cpCode");
				if (tmpBig != null){
					tmpWinningResultInfo.setCpCode(tmpBig.longValue());
				}
				
				tmpWinningTime = (Date)tmpMap.get("winningTime");
				tmpWinningResultInfo.setAccount((String)tmpMap.get("account"));
				tmpWinningResultInfo.setCardNo((String)tmpMap.get("cardNo"));
				tmpWinningResultInfo.setCardPwd((String)tmpMap.get("cardPwd"));
				tmpWinningResultInfo.setMobile((String)tmpMap.get("mobile"));
				if (tmpWinningTime != null){
					tmpWinningResultInfo.setWinningTime(DateFormatUtil.format(tmpWinningTime));
				}
				
				tmpBig = (BigInteger) tmpMap.get("prizeId");
				if (tmpBig != null){
					prizeId = tmpBig.longValue();
					tmpTPrize = tmpPrizeMap.get(prizeId);
					if (tmpTPrize == null){
						tmpListObjectMap = entityDao.getScrollDataBySql(String.format(tmpSql, prizeId), null, -1, -1);
						if (tmpListObjectMap == null || tmpListObjectMap.isEmpty()){
							continue;
						}
						tmpObjectMap = tmpListObjectMap.get(0);
						tmpTPrize = new TPrize();
						tmpTPrize.setCode((String)tmpObjectMap.get("prizeCode"));
						tmpTPrize.setLevel((Integer)tmpObjectMap.get("prizeLevel"));
						tmpTPrize.setName((String)tmpObjectMap.get("prizeName"));
						tmpTPrize.setPicture((String)tmpObjectMap.get("prizePicture"));
						
						tmpPrizeMap.put(prizeId, tmpTPrize);
					}
					
					tmpWinningResultInfo.setPrizeCode(tmpTPrize.getCode());
					tmpWinningResultInfo.setPrizeLevel(tmpTPrize.getLevel());
					tmpWinningResultInfo.setPrizeName(tmpTPrize.getName());
					if (!StringUtils.isBlank(tmpTPrize.getPicture())){
						tmpWinningResultInfo.setPrizePicture(getHttpUrl(tmpTPrize.getPicture()));
					}
					
				}
				tmpListWinningResultInfo.add(tmpWinningResultInfo);
			}
			
			resp.setWinningResultInfos(tmpListWinningResultInfo);
			resp.setRecordSize(tmpIntCount);
			logger.info("获取奖品列表成功");
		} catch (Exception e) {
			logger.error("获取奖品列表失败，程序异常，", e);
			resp.setResultCode(LuckyDrawResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("获取奖品列表失败，程序异常！");
		}
		return resp;
	}
	
	public GetWinningResultListResp getWinningResultListByPrizeCode(String prizeCode, int firstIndex, int maxResult){
		GetWinningResultListResp resp = new GetWinningResultListResp();
		logger.info("getWinningResultListByPrizeCode prizeCode="+prizeCode);
		String resultDesc = String.format("奖品编码[%s]非法！", prizeCode);
		if (StringUtils.isBlank(prizeCode)){
			logger.error(resultDesc);
			resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc(resultDesc);
			return resp;
		}
		try {
			TPrize tmpTPrize = entityDao.get(TPrize.class, "o.code=?1", new Object[]{prizeCode});
			if (tmpTPrize == null){
				logger.error(resultDesc);
				resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
				resp.setResultDesc(resultDesc);
				return resp;
			}
			
			String tmpSql = "select count(o.ID) as count from t_winning_result o where o.PRIZE_ID=" + tmpTPrize.getId();
			List<Map<String, Object>> tmpListMap = entityDao.getScrollDataBySql(tmpSql, null, -1, -1);
			int tmpIntCount = 0;
			if (tmpListMap != null && !tmpListMap.isEmpty()){
				Map<String, Object> tmpMapCount = tmpListMap.get(0);
				BigInteger tmpLongCount = (BigInteger) tmpMapCount.get("count");
				tmpIntCount = tmpLongCount.intValue();
			}
			if(tmpIntCount <= 0) return resp;
			
			
			tmpSql = "select o.PRIZE_ID as prizeId,o.ACCOUNT as account,o.MOBILE as mobile, o.WINNING_TIME as winningTime,"
					+ "o.CP_CODE as cpCode,o.CARD_NO as cardNo,o.CARD_PWD as cardPwd from t_winning_result o "
					+ "where o.PRIZE_ID=" + tmpTPrize.getId() + " order by o.WINNING_TIME desc";
			tmpListMap = entityDao.getScrollDataBySql(tmpSql, null, firstIndex, maxResult);
			if (tmpListMap == null || tmpListMap.isEmpty()){
				return resp;
			}
			List<GetWinningResultListResp.WinningResultInfo> tmpListWinningResultInfo = new ArrayList<GetWinningResultListResp.WinningResultInfo>();
			GetWinningResultListResp.WinningResultInfo tmpWinningResultInfo;
			TActivity tmpTActivity = tmpTPrize.getTactivity();
			Date tmpWinningTime;
			BigInteger tmpBig;
			for (Map<String, Object> tmpMap : tmpListMap){
				tmpWinningResultInfo = new GetWinningResultListResp.WinningResultInfo();
				if (tmpTActivity != null){
					tmpWinningResultInfo.setActivityCode(tmpTActivity.getCode());
					tmpWinningResultInfo.setActivityName(tmpTActivity.getName());
				}
				tmpBig = (BigInteger)tmpMap.get("cpCode");
				if (tmpBig != null){
					tmpWinningResultInfo.setCpCode(tmpBig.longValue());
				}
				tmpWinningTime = (Date)tmpMap.get("winningTime");
				tmpWinningResultInfo.setAccount((String)tmpMap.get("account"));
				tmpWinningResultInfo.setCardNo((String)tmpMap.get("cardNo"));
				tmpWinningResultInfo.setCardPwd((String)tmpMap.get("cardPwd"));
				tmpWinningResultInfo.setMobile((String)tmpMap.get("mobile"));
				if (tmpWinningTime != null){
					tmpWinningResultInfo.setWinningTime(DateFormatUtil.format(tmpWinningTime));
				}
				tmpWinningResultInfo.setPrizeCode(tmpTPrize.getCode());
				tmpWinningResultInfo.setPrizeLevel(tmpTPrize.getLevel());
				tmpWinningResultInfo.setPrizeName(tmpTPrize.getName());
				if (!StringUtils.isBlank(tmpTPrize.getPicture())){
					tmpWinningResultInfo.setPrizePicture(getHttpUrl(tmpTPrize.getPicture()));
				}
				
				tmpListWinningResultInfo.add(tmpWinningResultInfo);
			}
			resp.setWinningResultInfos(tmpListWinningResultInfo);
			resp.setRecordSize(tmpIntCount);
			logger.info("获取奖品列表成功");
		} catch (Exception e) {
			logger.error("获取奖品列表失败，程序异常，", e);
			resp.setResultCode(LuckyDrawResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("获取奖品列表失败，程序异常！");
		}
		return resp;
	}
	@Transactional
	public LuckyDrawResp luckyDraw(String activityCode, String userID, int limitWinNum) {
		logger.info("抽奖 activityCode="+activityCode+",userID="+userID+",limitWinNum="+limitWinNum);
		LuckyDrawResp resp = new LuckyDrawResp();
		Date currentDate = new Date();
		
		try {
			/**
			  * 验证活动有效性
			  */
			 ValidateRets<TActivity>  tmpTActivityValidateRets = activityValidate.validate(new ActivityValidateArgs(resp, activityCode, currentDate));
			 if (!tmpTActivityValidateRets.isSuccess()) return resp;
			 TActivity tmpTActivity = tmpTActivityValidateRets.getEntity();
			 Long tmpCpCode = tmpTActivity.getCpCode();
			
			 //是否必中：0-否，1-必中
			 int tmpFlagWinning = tmpTActivity.getFlagWinning() == null ? 0 : tmpTActivity.getFlagWinning();
			 logger.info("活动code："+activityCode+"，活动名："+tmpTActivity.getName()+"是否必中：0-否，1-必中,flagWinning="+tmpFlagWinning+",活动CpCode="+tmpCpCode);
			 /**
			  * 验证奖品有效性
			  */
			 String tmpSql;
			 if (tmpFlagWinning == 0) {
				 tmpSql = "select o.ID as id,o.CODE as code,o.NAME as name,o.TYPE as type,o.LEVEL as level, o.LIMIT_NUM as limitNum,"
							+ "o.NUMBER as number,o.WINNING_NUM as winningNum,o.PRICE as price,o.ODDS as odds,o.CREATE_TIME as createTime,"
							+ "o.STATUS as status,o.ACTIVITY_ID as activityId,o.CP_CODE as cpCode,o.PICTURE as picture,o.VERCTRL as verctrl"
							+ " from t_prize o where o.ACTIVITY_ID=" + tmpTActivity.getId() + " and o.STATUS=1 order by o.LEVEL asc";
			 } else {
				 tmpSql = "select o.ID as id,o.CODE as code,o.NAME as name,o.TYPE as type,o.LEVEL as level, o.LIMIT_NUM as limitNum,"
							+ "o.NUMBER as number,o.WINNING_NUM as winningNum,o.PRICE as price,o.ODDS as odds,o.CREATE_TIME as createTime,"
							+ "o.STATUS as status,o.ACTIVITY_ID as activityId,o.CP_CODE as cpCode,o.PICTURE as picture,o.VERCTRL as verctrl"
							+ " from t_prize o where o.ACTIVITY_ID=" + tmpTActivity.getId() + " and o.STATUS=1 and"
							+ " ((o.LIMIT_NUM=1 and o.NUMBER>o.WINNING_NUM) or o.LIMIT_NUM=0) order by o.LEVEL asc";
			 }
			 
			 List<Map<String, Object>> tmpListMap = entityDao.getScrollDataBySql(tmpSql, null, -1, -1);
			 if (tmpListMap == null || tmpListMap.isEmpty()){
				logger.error("奖品已抽完！");
				resp.setResultCode(LuckyDrawResultCode.PRIZE_IS_EMPTY);
				resp.setResultDesc("奖品已抽完！");
				return resp;
			 }
			 
			 List<TPrize> tmpListTPrize = new ArrayList<TPrize>();
			 TPrize tmpTPrize;
			 BigInteger tmpBig;
			 for (Map<String, Object> tmpMap : tmpListMap){
				tmpTPrize = new TPrize();
				tmpTPrize.setCode((String)tmpMap.get("code"));
				tmpBig = (BigInteger)tmpMap.get("cpCode");
				if (tmpBig != null){
					tmpTPrize.setCpCode(tmpBig.longValue());
				}
				tmpTPrize.setCreateTime((Date)tmpMap.get("createTime"));
				tmpBig = (BigInteger)tmpMap.get("id");
				if (tmpBig != null){
					tmpTPrize.setId(tmpBig.longValue());
				}
				tmpTPrize.setLevel((Integer)tmpMap.get("level"));
				tmpTPrize.setLimitNum((Integer)tmpMap.get("limitNum"));
				tmpTPrize.setName((String)tmpMap.get("name"));
				tmpTPrize.setNumber((Integer)tmpMap.get("number"));
				tmpTPrize.setOdds((Float)tmpMap.get("odds"));
				tmpTPrize.setPicture((String)tmpMap.get("picture"));
				tmpTPrize.setPrice((Integer)tmpMap.get("price"));
				tmpTPrize.setStatus((Integer)tmpMap.get("status"));
				tmpTPrize.setTactivity(tmpTActivity);
				tmpTPrize.setType((Integer)tmpMap.get("type"));
				tmpTPrize.setVerctrl((Integer)tmpMap.get("verctrl"));
				tmpTPrize.setWinningNum((Integer)tmpMap.get("winningNum"));
				
				tmpListTPrize.add(tmpTPrize);
			 }
			 
			 /**
			  * 验证用户有效性
			  */
			 ValidateRets<TUser> tmpTUserValidateRets = userDrawValidate.validate(new UserValidateArgs(resp, tmpTActivity, userID, limitWinNum, currentDate));
			 if (!tmpTUserValidateRets.isSuccess()) {
				 logger.info("验证用户无效["+userID+"]");
				 return resp;
			 }
			 TUser tmpTUser = tmpTUserValidateRets.getEntity();
			 
			 /**
			  * 更新用户可用积分
			  */
			 Integer tmpAvailablePoint = tmpTUser.getAvailablePoint() == null ? 0 : tmpTUser.getAvailablePoint();
			 Integer tmpUseupPoint = tmpTActivity.getUseupPoint() == null ? 0 : tmpTActivity.getUseupPoint();
			 tmpAvailablePoint = tmpAvailablePoint - tmpUseupPoint;
			 if (tmpUseupPoint > 0){
				 tmpTUser.setAvailablePoint(tmpAvailablePoint);
				 entityDao.update(tmpTUser);
			 }
			 
			 /**
			  * 验证中奖规则
			  */
			 ValidateRets<TWinningRule> tmpTWinningRuleValidateRets = winningRuleValidate.validate(new WinningRuleValidateArgs(resp, tmpTActivity.getId(), currentDate, tmpCpCode));
			 if (!tmpTWinningRuleValidateRets.isSuccess()) {
				 logger.info("活动["+tmpTActivity.getId()+"]，当前时间："+currentDate+"中奖规则无");
				 return resp;
			 }
			 
			 TWinningRule tmpTWinningRule = tmpTWinningRuleValidateRets.getEntity();
			 if(tmpTWinningRule != null){
				 tmpTPrize = tmpTWinningRule.getTprize();
				 /**
				  * 中奖了
				  */
				 logger.info("---中奖规则抽奖");
				 prizeService.luckyDraw(new LuckyDrawArgs(resp, tmpTPrize, tmpTUser, tmpTActivity, currentDate));
				 return resp;
			 }
			 
			 logger.info("===按奖品概率计算中奖");
			 
			 /**
			  * 按奖品概率计算中奖
			  */
			 int tmpBase = 10000;
			 int tmpRandNum = (int)(1+Math.random()*(tmpBase));
			 float tmpFloatOdds;
			 int tmpIntOdds;
			 int cumulativeBeforeNum = 0;
			 int cumulativeAfterNum = 0;
			 int tmpTPrizeSize = tmpListTPrize.size();
			 /*for (int i = 0; i < tmpTPrizeSize ; i ++){
				 tmpTPrize = tmpListTPrize.get(i);
				 tmpFloatOdds  = tmpTPrize.getOdds() == null ? 0.0f : tmpTPrize.getOdds();
				 if (tmpFloatOdds <= 0) continue;
				 tmpIntOdds = (int) (tmpFloatOdds *  100);
				 cumulativeBeforeNum = cumulativeAfterNum;
				 cumulativeAfterNum = cumulativeBeforeNum + tmpIntOdds;
				 if (tmpRandNum > cumulativeBeforeNum && tmpRandNum <= cumulativeAfterNum){
					 *//**
					  * 中奖了
					  *//*
					prizeService.luckyDraw(new LuckyDrawArgs(resp, tmpTPrize, tmpTUser, tmpTActivity, currentDate));
					if (resp.getResultCode() != ResultCode.SUCCESS) {
						if (i == (tmpTPrizeSize - 1)) {
							return resp;
						}else{
							continue;
						}
					}
					return resp;
				 }
			 }*/
			 logger.info("概率随机数="+tmpRandNum);
			 for (int i = 0; i < tmpTPrizeSize ; i ++){
				 tmpTPrize = tmpListTPrize.get(i);
				 tmpFloatOdds  = tmpTPrize.getOdds() == null ? 0.0f : tmpTPrize.getOdds();
				 if (tmpFloatOdds <= 0) continue;
				 tmpIntOdds = (int) (tmpFloatOdds *  100);
				 cumulativeBeforeNum = cumulativeAfterNum;
				 cumulativeAfterNum = cumulativeBeforeNum + tmpIntOdds;
				 if (tmpRandNum > cumulativeBeforeNum && tmpRandNum <= cumulativeAfterNum){
					 /**
					  * 中奖了
					  */
					 logger.info("头区间值："+cumulativeBeforeNum+",尾区间值："+cumulativeAfterNum);
					prizeService.luckyDraw(new LuckyDrawArgs(resp, tmpTPrize, tmpTUser, tmpTActivity, currentDate));
					return resp;
				 } else {
					 /**
					  * 必中情况下，要解决的问题是在随机落点未命中任何一个奖品时，抽取奖品列表ListTPrize最后一个奖品作为发放，
					  */
					 logger.info("是否必中：0-否，1-必中,flagWinning="+tmpFlagWinning+",奖品数："+tmpTPrizeSize+",必中情况下，要解决的问题是在随机落点未命中任何一个奖品时，抽取奖品列表ListTPrize最后一个奖品作为发放");
					 if (tmpFlagWinning != 0 && i == tmpTPrizeSize -1 ) {
						 /**
						  * 中奖了
						  */
						prizeService.luckyDraw(new LuckyDrawArgs(resp, tmpTPrize, tmpTUser, tmpTActivity, currentDate));
						return resp;
					 } 
				 }
			 }
			 logger.info("谢谢参与！");
			 resp.setResultCode(LuckyDrawResultCode.THANK_YOU_IN);
			 resp.setResultDesc("谢谢参与！");
		} catch (Exception e) {
			logger.error("抽奖失败，程序异常，luckyDraw activityCode="+activityCode+",userID"+userID+",limitWinNum="+limitWinNum, e);
			resp.setResultCode(LuckyDrawResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("抽奖失败，程序异常！");
		}
		return resp;
		
	}
	
	/**
	 * 抽奖记录
	 * @param activityCode
	 * @param firstIndex
	 * @param maxResult
	 * @return
	 */
	public GetDrawRecordResp getDrawRecord(String activityCode, int firstIndex, int maxResult){
		GetDrawRecordResp resp = new GetDrawRecordResp();
		logger.info("getDrawRecord activityCode="+activityCode);
		try{
			String resultDesc = String.format("活动编码[%s]非法！", activityCode);
			if (StringUtils.isBlank(activityCode)){
				logger.error(resultDesc);
				resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
				resp.setResultDesc(resultDesc);
				return resp;
			}
			TActivity tmpTActivity = entityDao.get(TActivity.class, "o.code=?1", new Object[]{activityCode});
			if (tmpTActivity == null){
				logger.error(resultDesc);
				resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
				resp.setResultDesc(resultDesc);
				return resp;
			}
			String tmpSql = "select count(o.ID) as count from t_draw_record o where o.ACTIVITY_ID=" + tmpTActivity.getId();
			List<Map<String, Object>> tmpListMap = entityDao.getScrollDataBySql(tmpSql, null, -1, -1);
			int tmpIntCount = 0;
			if (tmpListMap != null && !tmpListMap.isEmpty()){
				Map<String, Object> tmpMapCount = tmpListMap.get(0);
				BigInteger tmpLongDrawCount = (BigInteger) tmpMapCount.get("count");
				tmpIntCount = tmpLongDrawCount.intValue();
			}
			if (tmpIntCount <= 0) return resp;
			
			tmpSql = "select o.ACCOUNT as account,o.MOBILE as mobile,o.DRAW_TIME as drawTime,"
					+ "o.CP_CODE as cpCode from t_draw_record o "
					+ "where o.ACTIVITY_ID=" + tmpTActivity.getId() + " order by o.DRAW_TIME desc";
			tmpListMap = entityDao.getScrollDataBySql(tmpSql, null, firstIndex, maxResult);
			if (tmpListMap == null || tmpListMap.isEmpty()){
				return resp;
			}
			List<GetDrawRecordResp.DrawRecordInfo> tmpListDrawRecordInfo = new ArrayList<GetDrawRecordResp.DrawRecordInfo>();
			GetDrawRecordResp.DrawRecordInfo tmpDrawRecordInfo;
			Date tmpDrawTime;
			for (Map<String, Object> tmpMap : tmpListMap){
				tmpDrawRecordInfo = new GetDrawRecordResp.DrawRecordInfo();
				tmpDrawRecordInfo.setActivityName(tmpTActivity.getName());
				tmpDrawTime = (Date)tmpMap.get("drawTime");
				if (tmpDrawTime != null){
					tmpDrawRecordInfo.setDrawTime(DateFormatUtil.format(tmpDrawTime));
				}
				tmpDrawRecordInfo.setMobile((String)tmpMap.get("mobile"));
				tmpDrawRecordInfo.setUserID((String)tmpMap.get("account"));
				
				tmpListDrawRecordInfo.add(tmpDrawRecordInfo);
			}
			resp.setDrawRecordInfos(tmpListDrawRecordInfo);
			resp.setRecordSize(tmpIntCount);
			logger.info("获取抽奖记录成功");
		}catch(Exception e){
			logger.error("获取抽奖记录失败，程序异常，", e);
			resp.setResultCode(LuckyDrawResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("获取抽奖记录失败，程序异常！");
		}
		return resp;
	}

	/**
	 * 用户的 活动的中奖记录
	 * @param userID
	 * @param activityCode
	 * @param firstIndex
	 * @param maxResult
	 * @return
	 */
	public GetWinningResultListResp getWinningResultListByUserID(String userID,
			String activityCode, int firstIndex, int maxResult) {
		logger.info("获取中奖记录，活动Code="+activityCode+",userID="+userID);
		GetWinningResultListResp resp = new GetWinningResultListResp();
		String resultDesc;
		if (StringUtils.isBlank(userID)){
			resultDesc = String.format("用户账号[%s]非法！", userID);
			logger.error(resultDesc);
			resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc(resultDesc);
			return resp;
		}
		if (StringUtils.isBlank(activityCode)){
			resultDesc = String.format("活动编码[%s]非法！", activityCode);
			logger.error(resultDesc);
			resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc(resultDesc);
			return resp;
		}
		String tmp = "-1";
		try {
			TActivity tmpTActivity;
			String tmpActivityIds = "";
			String[] tmpActivityCodes = activityCode.split(",");
			List<Map<String, Object>> tmpListMap;
			Map<Long, TActivity> tmpIdActLinkMap = new HashMap<Long, TActivity>();
			String tmpSql;
			Object[] tmpQueryParams = new Object[]{userID};
			if (tmpActivityCodes.length == 1){
				if (activityCode.equals(tmp)){
					tmpSql = "select count(o.ID) as count from t_winning_result o where o.ACCOUNT=?";
					tmpListMap = entityDao.getScrollDataBySql(tmpSql, tmpQueryParams, -1, -1);
				}else{
					tmpTActivity = entityDao.get(TActivity.class, "o.code=?1", new Object[]{activityCode});
					if (tmpTActivity == null){
						resultDesc = String.format("活动编码[%s]非法！", activityCode);
						logger.error(resultDesc);
						resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
						resp.setResultDesc(resultDesc);
						return resp;
					}
					tmpIdActLinkMap.put(tmpTActivity.getId(), tmpTActivity);
					tmpActivityIds = tmpTActivity.getId() + "";
					
					tmpSql = "select count(o.ID) as count from t_winning_result o where o.ACCOUNT=? and o.ACTIVITY_ID=" + tmpTActivity.getId();
					tmpListMap = entityDao.getScrollDataBySql(tmpSql, tmpQueryParams, -1, -1);
				}
			}else{
				String tmpActivityCode;
				for (int i=0; i<tmpActivityCodes.length;i++){
					tmpActivityCode = tmpActivityCodes[i];
					tmpTActivity = entityDao.get(TActivity.class, "o.code=?1", new Object[]{tmpActivityCode});
					if (tmpTActivity == null){
						resultDesc = String.format("活动编码[%s]非法！", tmpActivityCode);
						logger.error(resultDesc);
						resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
						resp.setResultDesc(resultDesc);
						return resp;
					}
					tmpIdActLinkMap.put(tmpTActivity.getId(), tmpTActivity);
					tmpActivityIds = tmpActivityIds + tmpTActivity.getId() + ",";
				}
				
				tmpActivityIds = StringUtils.removeEnd(tmpActivityIds, ",");
				tmpSql = "select count(o.ID) as count from t_winning_result o where o.ACCOUNT=? and o.ACTIVITY_ID in(" + tmpActivityIds + ")";
				tmpListMap = entityDao.getScrollDataBySql(tmpSql, tmpQueryParams, -1, -1);
			}
			 
			int tmpIntCount = 0;
			if (tmpListMap != null && !tmpListMap.isEmpty()){
				Map<String, Object> tmpMapCount = tmpListMap.get(0);
				BigInteger tmpLongCount = (BigInteger) tmpMapCount.get("count");
				tmpIntCount = tmpLongCount.intValue();
			}
			if(tmpIntCount <= 0) {
				resp.setWinningResultInfos(new ArrayList<GetWinningResultListResp.WinningResultInfo>());
				logger.error("没有中奖记录");
				return resp;
			}
			 
			tmpSql = "select o.id, o.ACTIVITY_ID as activityId,o.PRIZE_ID as prizeId,o.ACCOUNT as account,o.MOBILE as mobile, o.WINNING_TIME as winningTime,"
					+ "o.CP_CODE as cpCode,o.CARD_NO as cardNo,o.CARD_PWD as cardPwd from t_winning_result o ";
			if (tmpActivityCodes.length == 1){
				if (activityCode.equals(tmp)){
					tmpSql = tmpSql + " where o.ACCOUNT=? order by o.WINNING_TIME desc";
				}else{
					tmpSql = tmpSql + " where o.ACCOUNT=? and o.ACTIVITY_ID=" + NumberUtils.toLong(tmpActivityIds) + " order by o.WINNING_TIME desc";
				}
			}else{
				tmpSql = tmpSql + " where o.ACCOUNT=? and o.ACTIVITY_ID in (" + tmpActivityIds + ") order by o.WINNING_TIME desc";
			}
			tmpListMap = entityDao.getScrollDataBySql(tmpSql, tmpQueryParams, firstIndex, maxResult);
			if (tmpListMap == null || tmpListMap.isEmpty()){
				logger.error("====没有中奖记录");
				resp.setWinningResultInfos(new ArrayList<GetWinningResultListResp.WinningResultInfo>());
				return resp;
			}
			
			Map<Long, TPrize> tmpPrizeMap = new HashMap<Long, TPrize>();
			TPrize tmpTPrize;
			List<GetWinningResultListResp.WinningResultInfo> tmpListWinningResultInfo = new ArrayList<GetWinningResultListResp.WinningResultInfo>();
			GetWinningResultListResp.WinningResultInfo tmpWinningResultInfo;
			tmpSql = "select o.CODE as prizeCode,o.NAME as prizeName,o.LEVEL as prizeLevel,o.PICTURE as prizePicture "
				   + "from t_prize o where o.ID=%s";
			Long prizeId;
			List<Map<String, Object>> tmpListObjectMap;
			Map<String, Object> tmpObjectMap;
			Date tmpWinningTime;
			BigInteger tmpBig;
			for (Map<String, Object> tmpMap : tmpListMap){
				tmpWinningResultInfo = new GetWinningResultListResp.WinningResultInfo();
				tmpBig = (BigInteger)tmpMap.get("activityId");
				if (tmpBig != null){
					tmpTActivity = tmpIdActLinkMap.get(tmpBig.longValue());
					if (tmpTActivity != null){
						tmpWinningResultInfo.setActivityCode(tmpTActivity.getCode());
						tmpWinningResultInfo.setActivityName(tmpTActivity.getName());
					}
				}
				tmpBig = (BigInteger)tmpMap.get("cpCode");
				if (tmpBig != null){
					tmpWinningResultInfo.setCpCode(tmpBig.longValue());
				}
				
				tmpWinningTime = (Date)tmpMap.get("winningTime");
				tmpWinningResultInfo.setWinningResultId(String.valueOf(tmpMap.get("id")));
				tmpWinningResultInfo.setAccount((String)tmpMap.get("account"));
				tmpWinningResultInfo.setCardNo((String)tmpMap.get("cardNo"));
				tmpWinningResultInfo.setCardPwd((String)tmpMap.get("cardPwd"));
				tmpWinningResultInfo.setMobile((String)tmpMap.get("mobile"));
				if (tmpWinningTime != null){
					tmpWinningResultInfo.setWinningTime(DateFormatUtil.format(tmpWinningTime));
				}
				
				tmpBig = (BigInteger) tmpMap.get("prizeId");
				if (tmpBig != null){
					prizeId = tmpBig.longValue();
					tmpTPrize = tmpPrizeMap.get(prizeId);
					if (tmpTPrize == null){
						tmpListObjectMap = entityDao.getScrollDataBySql(String.format(tmpSql, prizeId), null, -1, -1);
						if (tmpListObjectMap == null || tmpListObjectMap.isEmpty()){
							continue;
						}
						tmpObjectMap = tmpListObjectMap.get(0);
						tmpTPrize = new TPrize();
						tmpTPrize.setCode((String)tmpObjectMap.get("prizeCode"));
						tmpTPrize.setLevel((Integer)tmpObjectMap.get("prizeLevel"));
						tmpTPrize.setName((String)tmpObjectMap.get("prizeName"));
						tmpTPrize.setPicture((String)tmpObjectMap.get("prizePicture"));
						
						tmpPrizeMap.put(prizeId, tmpTPrize);
					}
					
					tmpWinningResultInfo.setPrizeCode(tmpTPrize.getCode());
					tmpWinningResultInfo.setPrizeLevel(tmpTPrize.getLevel());
					tmpWinningResultInfo.setPrizeName(tmpTPrize.getName());
					if (!StringUtils.isEmpty(tmpTPrize.getPicture())){
						tmpWinningResultInfo.setPrizePicture(getHttpUrl(tmpTPrize.getPicture()));
					}
					
				}
				tmpListWinningResultInfo.add(tmpWinningResultInfo);
			}
			
			resp.setWinningResultInfos(tmpListWinningResultInfo);
			resp.setRecordSize(tmpIntCount);
			logger.info("根据活动Code="+activityCode+",userID="+userID+",获取奖品列表成功");
		} catch (Exception e) {
			logger.error("获取奖品列表失败，程序异常，", e);
			resp.setResultCode(LuckyDrawResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("获取奖品列表失败，程序异常！");
		}
		return resp;
		
	}

	/**
	 * 抽奖记录
	 * @param activityCode
	 * @param userID
	 * @return
	 */
	public GetDrawRecordCountResp getDrawRecordCount(String activityCode, String userID) {
		
		GetDrawRecordCountResp resp = new GetDrawRecordCountResp();
		resp.setDayDrawCount(0);
		try{
			if (StringUtils.isBlank(activityCode)){
				logger.error("活动编码非法！");
				resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
				resp.setResultDesc("活动编码非法！");
				return resp;
			}
			TActivity tmpTActivity = entityDao.get(TActivity.class, "o.code=?1", new Object[]{activityCode});
			if (tmpTActivity == null){
				logger.error("活动编码非法！");
				resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
				resp.setResultDesc("活动编码非法！");
				return resp;
			}
			String tmpSql = "select count(o.ID) as count from t_draw_record_day o where o.ACTIVITY_ID=? and o.ACCOUNT=? and date_format(o.DRAW_TIME,'%Y-%m-%d')=?";
			List<Map<String, Object>> tmpListMapCount = entityDao.getScrollDataBySql(tmpSql, new Object[]{tmpTActivity.getId(), userID, DateFormatUtil.format(new Date(), "yyyy-MM-dd")}, -1, -1);
			
			if (tmpListMapCount != null && !tmpListMapCount.isEmpty()){
				Map<String, Object> tmpMapCount = tmpListMapCount.get(0);
				BigInteger tmpBigDrawCount = (BigInteger) tmpMapCount.get("count");
				if (tmpBigDrawCount != null)
				resp.setDayDrawCount(tmpBigDrawCount.intValue());
			}
			logger.info("获取抽奖记录计数成功");
		}catch(Exception e){
			logger.error("获取抽奖记录计数失败，程序异常，", e);
			resp.setResultCode(LuckyDrawResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("获取抽奖记录计数失败，程序异常！");
		}
		return resp;
	}

	/**
	 * 根据手机号查询抽奖记录
	 * @param activityCode
	 * @param mobileNo
	 * @return
	 */
	public GetDrawRecordCountByMobileResp getDrawRecordCountByMobile(String activityCode, String mobileNo) {
		GetDrawRecordCountByMobileResp resp = new GetDrawRecordCountByMobileResp();
		resp.setDrawCount(0);
		try{
			if (StringUtils.isBlank(activityCode)){
				logger.error("活动编码非法！");
				resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
				resp.setResultDesc("活动编码非法！");
				return resp;
			}
			TActivity tmpTActivity = entityDao.get(TActivity.class, "o.code=?1", new Object[]{activityCode});
			if (tmpTActivity == null){
				logger.error("活动编码非法！");
				resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
				resp.setResultDesc("活动编码非法！");
				return resp;
			}
			Date tmpStartTime = tmpTActivity.getStartTime();
			Date tmpEndTime = tmpTActivity.getEndTime();
			
			String tmpSql = "select count(o.ID) as count from t_draw_record o where o.ACTIVITY_ID=? and o.ACCOUNT=? and date_format(o.DRAW_TIME,'%Y-%m-%d %H:%i:%s')>=? and date_format(o.DRAW_TIME,'%Y-%m-%d %H:%i:%s')<=?";
			List<Map<String, Object>> tmpListMapCount = entityDao.getScrollDataBySql(tmpSql, new Object[]{tmpTActivity.getId(), mobileNo, 
					DateFormatUtil.format(tmpStartTime, "yyyy-MM-dd HH:mm:ss"), DateFormatUtil.format(tmpEndTime, "yyyy-MM-dd HH:mm:ss")}, -1, -1);
			
			if (tmpListMapCount != null && !tmpListMapCount.isEmpty()){
				Map<String, Object> tmpMapCount = tmpListMapCount.get(0);
				BigInteger tmpBigDrawCount = (BigInteger) tmpMapCount.get("count");
				if (tmpBigDrawCount != null)
				resp.setDrawCount(tmpBigDrawCount.intValue());
			}
			logger.info("获取手机抽奖记录计数成功");
		}catch(Exception e){
			logger.error("获取手机抽奖记录计数失败，程序异常，", e);
			resp.setResultCode(LuckyDrawResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("获取手机抽奖记录计数失败，程序异常！");
		}
		return resp;
	}

	/**
	 * 根据手机号查询中奖
	 * @param activityCode
	 * @param mobileNo
	 * @return
	 */
	public GetWinningResultListResp getWinningResultListByMobile(String mobileNo, String activityCode, int firstIndex, int maxResult) {
		GetWinningResultListResp resp = new GetWinningResultListResp();
		String resultDesc;
		if (StringUtils.isBlank(mobileNo)){
			resultDesc = String.format("手机号[%s]非法！", mobileNo);
			logger.error(resultDesc);
			resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc(resultDesc);
			return resp;
		}
		if (StringUtils.isBlank(activityCode)){
			resultDesc = String.format("活动编码[%s]非法！", activityCode);
			logger.error(resultDesc);
			resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
			resp.setResultDesc(resultDesc);
			return resp;
		}
		String tmp = "-1";
		try {
			TActivity tmpTActivity;
			String tmpActivityIds = "";
			String[] tmpActivityCodes = activityCode.split(",");
			List<Map<String, Object>> tmpListMap;
			Map<Long, TActivity> tmpIdActLinkMap = new HashMap<Long, TActivity>();
			String tmpSql;
			Object[] tmpQueryParams = new Object[]{mobileNo}; 
			if (tmpActivityCodes.length == 1){
				if (activityCode.equals(tmp)){
					tmpSql = "select count(o.ID) as count from t_winning_result o where o.MOBILE=?";
					tmpListMap = entityDao.getScrollDataBySql(tmpSql, tmpQueryParams, -1, -1);
				}else{
					tmpTActivity = entityDao.get(TActivity.class, "o.code=?1", new Object[]{activityCode});
					if (tmpTActivity == null){
						resultDesc = String.format("活动编码[%s]非法！", activityCode);
						logger.error(resultDesc);
						resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
						resp.setResultDesc(resultDesc);
						return resp;
					}
					tmpIdActLinkMap.put(tmpTActivity.getId(), tmpTActivity);
					tmpActivityIds = tmpTActivity.getId() + "";
					
					tmpSql = "select count(o.ID) as count from t_winning_result o where o.MOBILE=? and o.ACTIVITY_ID=" + tmpTActivity.getId();
					tmpListMap = entityDao.getScrollDataBySql(tmpSql, tmpQueryParams, -1, -1);
				}
			}else{
				String tmpActivityCode;
				for (int i=0; i<tmpActivityCodes.length;i++){
					tmpActivityCode = tmpActivityCodes[i];
					tmpTActivity = entityDao.get(TActivity.class, "o.code=?1", new Object[]{tmpActivityCode});
					if (tmpTActivity == null){
						resultDesc = String.format("活动编码[%s]非法！", tmpActivityCode);
						logger.error(resultDesc);
						resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
						resp.setResultDesc(resultDesc);
						return resp;
					}
					tmpIdActLinkMap.put(tmpTActivity.getId(), tmpTActivity);
					tmpActivityIds = tmpActivityIds + tmpTActivity.getId() + ",";
				}
				
				tmpActivityIds = StringUtils.removeEnd(tmpActivityIds, ",");
				tmpSql = "select count(o.ID) as count from t_winning_result o where o.MOBILE=? and o.ACTIVITY_ID in(" + tmpActivityIds + ")";
				tmpListMap = entityDao.getScrollDataBySql(tmpSql, tmpQueryParams, -1, -1);
			}
			 
			int tmpIntCount = 0;
			if (tmpListMap != null && !tmpListMap.isEmpty()){
				Map<String, Object> tmpMapCount = tmpListMap.get(0);
				BigInteger tmpLongCount = (BigInteger) tmpMapCount.get("count");
				tmpIntCount = tmpLongCount.intValue();
			}
			if(tmpIntCount <= 0) return resp;
			 
			tmpSql = "select o.ACTIVITY_ID as activityId,o.PRIZE_ID as prizeId,o.ACCOUNT as account,o.MOBILE as mobile, o.WINNING_TIME as winningTime,"
					+ "o.CP_CODE as cpCode,o.CARD_NO as cardNo,o.CARD_PWD as cardPwd from t_winning_result o ";
			if (tmpActivityCodes.length == 1){
				if (activityCode.equals(tmp)){
					tmpSql = tmpSql + " where o.MOBILE=? order by o.WINNING_TIME desc";
				}else{
					tmpSql = tmpSql + " where o.MOBILE=? and o.ACTIVITY_ID=" + NumberUtils.toLong(tmpActivityIds) + " order by o.WINNING_TIME desc";
				}
			}else{
				tmpSql = tmpSql + " where o.MOBILE=? and o.ACTIVITY_ID in (" + tmpActivityIds + ") order by o.WINNING_TIME desc";
			}
			tmpListMap = entityDao.getScrollDataBySql(tmpSql, tmpQueryParams, firstIndex, maxResult);
			if (tmpListMap == null || tmpListMap.isEmpty()){
				return resp;
			}
			
			Map<Long, TPrize> tmpPrizeMap = new HashMap<Long, TPrize>();
			TPrize tmpTPrize;
			List<GetWinningResultListResp.WinningResultInfo> tmpListWinningResultInfo = new ArrayList<GetWinningResultListResp.WinningResultInfo>();
			GetWinningResultListResp.WinningResultInfo tmpWinningResultInfo;
			tmpSql = "select o.CODE as prizeCode,o.NAME as prizeName,o.LEVEL as prizeLevel,o.PICTURE as prizePicture "
				   + "from t_prize o where o.ID=%s";
			Long prizeId;
			List<Map<String, Object>> tmpListObjectMap;
			Map<String, Object> tmpObjectMap;
			Date tmpWinningTime;
			BigInteger tmpBig;
			for (Map<String, Object> tmpMap : tmpListMap){
				tmpWinningResultInfo = new GetWinningResultListResp.WinningResultInfo();
				tmpBig = (BigInteger)tmpMap.get("activityId");
				if (tmpBig != null){
					tmpTActivity = tmpIdActLinkMap.get(tmpBig.longValue());
					if (tmpTActivity != null){
						tmpWinningResultInfo.setActivityCode(tmpTActivity.getCode());
						tmpWinningResultInfo.setActivityName(tmpTActivity.getName());
					}
				}
				tmpBig = (BigInteger)tmpMap.get("cpCode");
				if (tmpBig != null){
					tmpWinningResultInfo.setCpCode(tmpBig.longValue());
				}
				
				tmpWinningTime = (Date)tmpMap.get("winningTime");
				tmpWinningResultInfo.setAccount((String)tmpMap.get("account"));
				tmpWinningResultInfo.setCardNo((String)tmpMap.get("cardNo"));
				tmpWinningResultInfo.setCardPwd((String)tmpMap.get("cardPwd"));
				tmpWinningResultInfo.setMobile((String)tmpMap.get("mobile"));
				if (tmpWinningTime != null){
					tmpWinningResultInfo.setWinningTime(DateFormatUtil.format(tmpWinningTime));
				}
				
				tmpBig = (BigInteger) tmpMap.get("prizeId");
				if (tmpBig != null){
					prizeId = tmpBig.longValue();
					tmpTPrize = tmpPrizeMap.get(prizeId);
					if (tmpTPrize == null){
						tmpListObjectMap = entityDao.getScrollDataBySql(String.format(tmpSql, prizeId), null, -1, -1);
						if (tmpListObjectMap == null || tmpListObjectMap.isEmpty()){
							continue;
						}
						tmpObjectMap = tmpListObjectMap.get(0);
						tmpTPrize = new TPrize();
						tmpTPrize.setCode((String)tmpObjectMap.get("prizeCode"));
						tmpTPrize.setLevel((Integer)tmpObjectMap.get("prizeLevel"));
						tmpTPrize.setName((String)tmpObjectMap.get("prizeName"));
						tmpTPrize.setPicture((String)tmpObjectMap.get("prizePicture"));
						
						tmpPrizeMap.put(prizeId, tmpTPrize);
					}
					
					tmpWinningResultInfo.setPrizeCode(tmpTPrize.getCode());
					tmpWinningResultInfo.setPrizeLevel(tmpTPrize.getLevel());
					tmpWinningResultInfo.setPrizeName(tmpTPrize.getName());
					if (!StringUtils.isEmpty(tmpTPrize.getPicture())){
						tmpWinningResultInfo.setPrizePicture(getHttpUrl(tmpTPrize.getPicture()));
					}
					
				}
				tmpListWinningResultInfo.add(tmpWinningResultInfo);
			}
			resp.setWinningResultInfos(tmpListWinningResultInfo);
			resp.setRecordSize(tmpIntCount);
			logger.info("获取奖品列表成功");
		} catch (Exception e) {
			logger.error("获取奖品列表失败，程序异常，", e);
			resp.setResultCode(LuckyDrawResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("获取奖品列表失败，程序异常！");
		}
		return resp;
	}
	
	@Transactional
	public UpdateWinningResultResp updateWinningResult(Long winningResultId, String mobileNo) {
		UpdateWinningResultResp resp = new UpdateWinningResultResp();
		try{
			if (winningResultId == null){
				logger.error("更新中奖结果失败，参数[winningResultId]非法！");
				resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
				resp.setResultDesc("更新中奖结果失败，参数[winningResultId]非法！");
				return resp;
			}
			if (StringUtils.isEmpty(mobileNo)){
				logger.error("更新中奖结果失败，参数[mobileNo]非法！");
				resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
				resp.setResultDesc("更新中奖结果失败，参数[mobileNo]非法！");
				return resp;
			}
			TWinningResult tmpTWinningResult = entityDao.get(TWinningResult.class, winningResultId);
			if (tmpTWinningResult == null) {
				logger.error("更新中奖结果失败，中奖数据不存在！");
				resp.setResultCode(LuckyDrawResultCode.PARAMETER_IS_NOT_LEGAL);
				resp.setResultDesc("更新中奖结果失败，中奖数据不存在！");
				return resp;
			}
			String tmpSrcMobile = tmpTWinningResult.getMobile();
			boolean update = false;
			if (StringUtils.isBlank(tmpSrcMobile)) {
				update = true;
			} else {
				if (!tmpSrcMobile.equals(mobileNo)) {
					update = true;
				}
			}
			if (update) {
				tmpTWinningResult.setMobile(mobileNo);
				entityDao.update(tmpTWinningResult);
			}
			logger.info("更新中奖结果成功");
		}catch(Exception e){
			logger.error("更新中奖结果失败，程序异常，", e);
			resp.setResultCode(LuckyDrawResultCode.APPLICATION_EXCEPTION);
			resp.setResultDesc("更新中奖结果失败，程序异常！");
		}
		return resp;
	}
}
